<template>
  <div class="auth-container">
    <div class="auth-box">
      <div class="auth-header">
        <div class="login-logo" style="margin-bottom: 40px;">
          <Logo />
        </div>

      </div>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="auth-form" @keyup.enter="handleLogin">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" :prefix-icon="User" placeholder="请输入用户名">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" :prefix-icon="Lock" type="password" placeholder="请输入密码" show-password>
          </el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input v-model="loginForm.captcha" :prefix-icon="Key" placeholder="请输入验证码">
            </el-input>
            <div class="captcha-image-wrapper" @click="refreshCaptcha">
              <img :src="captchaImage" class="captcha-image" alt="验证码" title="点击刷新验证码">
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="remember-row">
            <el-checkbox v-model="rememberAccount">记住账号密码</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" class="auth-button">
            {{ loading ? '登录中' : '登录' }}
          </el-button>
        </el-form-item>
        <div class="auth-links">
          <div  class="forget-link" @click.prevent="handleForgetPassword">忘记密码</div>
          <router-link to="/register">立即注册</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store/user'
import request from '@/utils/request'
import { User, Lock, Key } from '@element-plus/icons-vue'
import { setBackRoutes } from '@/router'
import { ElMessage } from 'element-plus'
import Logo from '@/components/common/Logo.vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const loginFormRef = ref(null)
const loading = ref(false)
const rememberAccount = ref(false)
const captchaImage = ref('')
const captchaKey = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名至少3个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 刷新验证码
const refreshCaptcha = async () => {
  try {
    const res = await request.get('/captcha/generate', null, {
      showDefaultMsg: false,
      onSuccess: (data) => {
        captchaImage.value = data.image
        captchaKey.value = data.key
      }
    })
  } catch (error) {
    ElMessage.error('获取验证码失败')
  }
}

// 页面加载时检查本地存储
onMounted(() => {
  const savedUsername = localStorage.getItem('rememberedUsername')
  const savedPassword = localStorage.getItem('rememberedPassword')
  const remembered = localStorage.getItem('rememberAccount')

  if (remembered === 'true' && savedUsername) {
    loginForm.username = savedUsername
    loginForm.password = savedPassword || ''
    rememberAccount.value = true
  }
  
  // 获取验证码
  refreshCaptcha()
})

const handleLogin = () => {
  loginFormRef.value.validate(async valid => {
    if (valid) {
      loading.value = true
      try {
        await request.post("/user/login", {
          ...loginForm,
          captchaKey: captchaKey.value
        }, {
          successMsg: null,
          onSuccess: async (data) => {
            // 处理记住账号密码
            if (rememberAccount.value) {
              localStorage.setItem('rememberedUsername', loginForm.username)
              localStorage.setItem('rememberedPassword', loginForm.password)
              localStorage.setItem('rememberAccount', 'true')
            } else {
              localStorage.removeItem('rememberedUsername')
              localStorage.removeItem('rememberedPassword')
              localStorage.setItem('rememberAccount', 'false')
            }

            // 如果是服务人员，先检查员工信息
            if (data.roleCode === 'STAFF') {
              let staffInfo = null
              try {
                const staffRes = await request.get(`/staff/user/${data.id}`, null, {
                  showDefaultMsg: false
                })
                staffInfo = staffRes
              } catch (error) {
                console.error('获取员工信息失败:', error)
              }

              // 统一处理员工信息检查结果
              if (!staffInfo) {
                ElMessage.error('获取员工信息失败，请联系管理员注册身份！')
                return
              }

              // 保存员工信息
              data.staffInfo = staffInfo
            }

            // 保存用户信息
            userStore.setUserInfo(data)

            // 根据角色进行不同的路由跳转
            if (data.roleCode === 'USER') {
              // 普通用户跳转到前台首页
              router.push(route.query.redirect || '/')
            } else {
              // 其他角色（管理员、员工等）跳转到后台
              userStore.setMenus(data.menuList)
              setBackRoutes()
              await router.isReady()
              router.push(route.query.redirect || '/back/dashboard')
            }
          },
          onError: (error) => {
            refreshCaptcha()
            console.error('登录失败:', error)
          }
        })
      } finally {
        loading.value = false
      }
    }
  })
}

const handleForgetPassword = () => {
  ElMessage.info('请联系管理员重置密码')
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/auth.scss";

.login-logo {
  transform: scale(1.5); // 放大1.5倍
  margin-bottom: 20px; // 增加底部间距
}

// 记住账号样式
.remember-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: -8px;

  :deep(.el-checkbox__label) {
    color: #606266;
    font-size: 14px;
  }
}

// 移除动画效果，保持简洁
:deep(.el-input__suffix) {
  color: #909399;
}
.forget-link{
  cursor: pointer;
  color: #909399;
  // xi
  font-size: 14px;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.captcha-image-wrapper {
  width: 100px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  flex-shrink: 0;
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.captcha-image-wrapper:hover {
  border-color: #409eff;
}
</style> 